<script setup>
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { userManager } from '@/utils/user';
import resourceService from '@/services/resourceService';
import { ElMessage, ElIcon,ElAvatar } from 'element-plus';
import { User } from '@element-plus/icons-vue';

// --- 状态定义 ---
const router = useRouter();
const loading = ref(false);
const activeTab = ref('created'); // 默认激活'我创建的'

// '我创建的' 资源的状态
const createdResources = ref([]);
const totalCreated = ref(0);
const createdCurrentPage = ref(1);
const createdPageSize = ref(12);

// '我加入的' 资源的状态
const joinedResources = ref([]);
const totalJoined = ref(0);
const joinedCurrentPage = ref(1);
const joinedPageSize = ref(12);


// --- 方法定义 ---

// 获取我创建的资源
const fetchCreatedResources = async () => {
  loading.value = true;
  const userId = userManager.getUserId();
  if (!userId) {
    ElMessage.error('无法获取用户信息，请重新登录');
    loading.value = false;
    return;
  }
  try {
    const response = await resourceService.getCreatedResources(userId, createdCurrentPage.value, createdPageSize.value);
    if (response && response.code === 1000) {
      createdResources.value = response.data.records;
      totalCreated.value = response.data.total;
    } else {
      ElMessage.error(response?.msg || '获取分享的资源列表失败');
      createdResources.value = [];
      totalCreated.value = 0;
    }
  } catch (error) {
    console.error('获取分享的资源网络请求错误:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 获取我加入的资源
const fetchJoinedResources = async () => {
  loading.value = true;
  const userId = userManager.getUserId();
  if (!userId) {
    ElMessage.error('无法获取用户信息，请重新登录');
    loading.value = false;
    return;
  }
  try {
    const response = await resourceService.getJoinedResources(userId, joinedCurrentPage.value, joinedPageSize.value);
    if (response && response.code === 1000) {
      joinedResources.value = response.data.records;
      totalJoined.value = response.data.total;
    } else {
      ElMessage.error(response?.msg || '获取购买的资源列表失败');
      joinedResources.value = [];
      totalJoined.value = 0;
    }
  } catch (error) {
    console.error('获取购买的资源网络请求错误:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 处理'我创建的'分页变化
const handleCreatedPageChange = (newPage) => {
  createdCurrentPage.value = newPage;
  fetchCreatedResources();
};

// 处理'我加入的'分页变化
const handleJoinedPageChange = (newPage) => {
  joinedCurrentPage.value = newPage;
  fetchJoinedResources();
};


// 处理点击资源卡片
const handleResourceClick = (resourceId) => {
  if (resourceId) {
    router.push(`/resource/${resourceId}`);
  }
};

// 监听 activeTab 的变化
watch(activeTab, (newTabName) => {
  if (newTabName === 'created' && createdResources.value.length === 0) {
    fetchCreatedResources();
  } else if (newTabName === 'joined' && joinedResources.value.length === 0) {
    fetchJoinedResources();
  }
}, {
  immediate: true // 确保组件加载后会立即执行一次
});

</script>

<template>
  <div class="my-resource-page" v-loading="loading">
    <div class="content-panel">
      <div class="page-header">
        <h1>我的资源</h1>
        <p>在这里管理您分享和购买的所有学习资源</p>
      </div>

      <el-tabs v-model="activeTab" class="resource-tabs">
        <el-tab-pane label="我分享的资源" name="created">
          <div class="tab-content-wrapper">
            <el-row :gutter="24" v-if="createdResources.length > 0">
              <el-col :xs="12" :sm="8" :md="6" v-for="resource in createdResources" :key="resource.id">
                <el-card shadow="never" class="resource-card" @click="handleResourceClick(resource.id)">
                  <div class="cover-image-wrapper">
                    <img :src="resource.coverImage || '/default-cover.png'" class="cover-image" alt="Resource Cover"/>
                  </div>
                  <div class="card-content">
                    <h4 class="title" :title="resource.title">{{ resource.title }}</h4>
                    <div class="meta">
                      <el-avatar :size="20" :src="resource.publisherAvatar" class="publisher-avatar">
                        <el-icon><User /></el-icon>
                      </el-avatar>
                      <span>{{ resource.publisherName || '匿名' }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <div v-else class="empty-wrapper">
              <el-empty v-if="!loading" description="您还没有分享任何资源"></el-empty>
            </div>
            <div class="pagination-container" v-if="totalCreated > createdPageSize">
              <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="totalCreated"
                  :page-size="createdPageSize"
                  :current-page="createdCurrentPage"
                  @current-change="handleCreatedPageChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="我购买的资源" name="joined">
          <div class="tab-content-wrapper">
            <el-row :gutter="24" v-if="joinedResources.length > 0">
              <el-col :xs="12" :sm="8" :md="6" v-for="resource in joinedResources" :key="resource.id">
                <el-card shadow="never" class="resource-card" @click="handleResourceClick(resource.id)">
                  <div class="cover-image-wrapper">
                    <img :src="resource.coverImage || '/default-cover.png'" class="cover-image" alt="Resource Cover"/>
                  </div>
                  <div class="card-content">
                    <h4 class="title" :title="resource.title">{{ resource.title }}</h4>
                    <div class="meta">
                      <el-avatar :size="20" :src="resource.publisherAvatar" class="publisher-avatar">
                        <el-icon><User /></el-icon>
                      </el-avatar>
                      <span>{{ resource.publisherName || '匿名' }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <div v-else class="empty-wrapper">
              <el-empty v-if="!loading" description="您还没有购买任何资源"></el-empty>
            </div>
            <div class="pagination-container" v-if="totalJoined > joinedPageSize">
              <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="totalJoined"
                  :page-size="joinedPageSize"
                  :current-page="joinedCurrentPage"
                  @current-change="handleJoinedPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>

/* 页面整体布局 */
.my-resource-page {
  padding: 24px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

/* 主内容面板 */
.content-panel {
  background-color: #fff;
  border-radius: 16px; /* 增大主面板圆角 */
  padding: 24px 32px;
  box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05); /* 更微妙的阴影 */
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
}
.page-header h1 {
  font-size: 22px; /* 调整字号 */
  font-weight: 500; /* 中等字重 */
  color: #202124; /* Google风格的深灰色 */
  margin-bottom: 8px;
}
.page-header p {
  font-size: 14px;
  color: #5f6368; /* Google风格的次要文字颜色 */
}

/* Tabs 样式 */
.resource-tabs {
  border: none;
}
.resource-tabs :deep(.el-tabs__header) {
  margin-bottom: 24px;
}
.resource-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px; /* 底部线条变细 */
}
.resource-tabs :deep(.el-tabs__active-bar) {
  height: 3px; /* 激活状态线条变粗 */
  border-radius: 3px;
}
.resource-tabs :deep(.el-tabs__item) {
  font-size: 15px; /* 调整Tab字体大小 */
}
.resource-tabs :deep(.el-tabs__content) {
  padding: 0;
}
.tab-content-wrapper {
  min-height: 400px;
}

/* 资源卡片样式 */
.resource-card {
  cursor: pointer;
  margin-bottom: 24px;
  border-radius: 12px;
  border: none; /* 移除边框，完全靠阴影 */
  box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 1px 3px 1px rgba(60,64,67,0.15); /* Material Design 风格阴影 */
  transition: box-shadow 0.3s ease;
  overflow: hidden;
  position: relative; /* 为悬停蒙层定位 */
}

/* Google 风格悬停效果：半透明蒙层 */
.resource-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none; /* 允许点击穿透蒙层 */
}
.resource-card:hover::after {
  opacity: 0.04; /* 非常淡的蒙层 */
}

.resource-card :deep(.el-card__body) {
  padding: 0;
}

/* 封面图 */
.cover-image-wrapper {
  width: 100%;
  padding-top: 56.25%;
  position: relative;
  overflow: hidden;
  background-color: #f1f3f4;
  border-bottom: 1px solid #e0e0e0;
}
.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}
.resource-card:hover .cover-image {
  transform: scale(1.05);
}

/* 卡片内容 */
.card-content {
  padding: 16px;
}
.title {
  margin: 0 0 10px 0;
  font-size: 1rem;
  font-weight: 500;
  color: #202124;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.meta {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #5f6368;
  gap: 6px;
}

/* 空状态 */
.empty-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 400px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px 0;
}
</style>